package com.vastcom.sigma.admin.tools;

import javax.imageio.ImageIO;
import java.awt.*;
import java.awt.image.BufferedImage;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.sql.Timestamp;
import java.text.DateFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
import java.util.UUID;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

public class Tools {
    public static String BASE_IMG_PREFIX="data:image/png;base64,";
    public static final String FGGZ_GLLX_FG="FG";
    public static final String FGGZ_GLLX_XG="XG";
    public static final String FGGZ_GLLX_GG="GG";
    public static final String GGRZSB_YBL="YBL";
    public static final String GGRZSB_WBL="WBL";
    public static final String GBGZXFJL_YCL="YCL";
    public static final String GBGZXFJL_WCL="WCL";

    public static final String INVENTORY_CHANGE_TYPE_ADD="ADD";
    public static final String INVENTORY_CHANGE_TYPE_OUT="OUT";
    public static final String INVENTORY_CHANGE_TYPE_MENUS="MENUS";

  /*  completeWrite
    singleWrite
    readOnly
    */

    public static String newUUID() {
        String uuid = UUID.randomUUID().toString();
        uuid = uuid.replace("-", "");
        return uuid;
    }

    /**
     * 验证字符串是否为null和"",满足返回true，不满足返回false
     *
     * @author aJie
     * @param str
     * @return boolean
     */
    public static boolean isNullOrSpace(String str) {
        return null == str || "".equals(str) ? true : false;
    }


    public static String getBetweenDateBystartTimeAndEndTime(Timestamp kssj, Timestamp jssj){
        //Calendar birthday = new GregorianCalendar(kssj.getYear(), 6, 1,0,0,0);//2010年10月12日，month从0开始  （6代表的是5月）
        Calendar birthday=Calendar.getInstance();
        birthday.setTimeInMillis(kssj.getTime());

        //Calendar now = new GregorianCalendar(2015, 5, 31,23,59,59);//2010年10月12日，month从0开始
        Calendar now =Calendar.getInstance();
        now.setTimeInMillis(System.currentTimeMillis());
        if(jssj!=null){
            now =Calendar.getInstance();
            now.setTimeInMillis(jssj.getTime());
        }
        int day = now.get(Calendar.DAY_OF_MONTH) - birthday.get(Calendar.DAY_OF_MONTH);
        int month = now.get(Calendar.MONTH) - birthday.get(Calendar.MONTH);
        int year = now.get(Calendar.YEAR) - birthday.get(Calendar.YEAR);
        //按照减法原理，先day相减，不够向month借；然后month相减，不够向year借；最后year相减。
        if(day<0){
            month -= 1;
            now.add(Calendar.MONTH, -1);//得到上一个月，用来得到上个月的天数。
            day = day + now.getActualMaximum(Calendar.DAY_OF_MONTH);
        }
        if(month<0){
            month = (month+12)%12;
            year--;
        }
        //System.out.println();


        return year+"年"+month+"月"+day+"天";
    }


    public static String getBetweenDateBystartDateAndEndDate(Date kssj, Date jssj){
        //Calendar birthday = new GregorianCalendar(kssj.getYear(), 6, 1,0,0,0);//2010年10月12日，month从0开始  （6代表的是5月）
        Calendar birthday=Calendar.getInstance();
        birthday.setTimeInMillis(kssj.getTime());

        //Calendar now = new GregorianCalendar(2015, 5, 31,23,59,59);//2010年10月12日，month从0开始
        Calendar now =Calendar.getInstance();
        now.setTimeInMillis(System.currentTimeMillis());
        if(jssj!=null){
            now =Calendar.getInstance();
            now.setTimeInMillis(jssj.getTime());
        }
        int day = now.get(Calendar.DAY_OF_MONTH) - birthday.get(Calendar.DAY_OF_MONTH);
        int month = now.get(Calendar.MONTH) - birthday.get(Calendar.MONTH);
        int year = now.get(Calendar.YEAR) - birthday.get(Calendar.YEAR);
        //按照减法原理，先day相减，不够向month借；然后month相减，不够向year借；最后year相减。
        if(day<0){
            month -= 1;
            now.add(Calendar.MONTH, -1);//得到上一个月，用来得到上个月的天数。
            day = day + now.getActualMaximum(Calendar.DAY_OF_MONTH);
        }
        if(month<0){
            month = (month+12)%12;
            year--;
        }
        //System.out.println();


        return year+"年"+month+"月"+day+"天";
    }


    public static Date convertToDate(String strDate, String format) {
        try {
            SimpleDateFormat sdf = new SimpleDateFormat(format);
            Date date = sdf.parse(strDate);
            return date;
        } catch (Exception e) {
            e.printStackTrace();
            return null;
        }
    }

    public static String convertDateToString(String format,Date date){
        DateFormat format1 = new SimpleDateFormat(format);
        return format1.format(date);
    }

    public static String long2Date(long lSysTime1 ){
        SimpleDateFormat sdf= new SimpleDateFormat("MM/dd/yyyy HH:mm:ss");
        //前面的lSysTime是秒数，先乘1000得到毫秒数，再转为java.util.Date类型
        Date dt = new Date(lSysTime1 * 1000);
        String sDateTime = sdf.format(dt);  //得到精确到秒的表示：08/31/2006 21:08:00
        return sDateTime;
    }


    public static long covertTimeStampToLong(String currentdate){

        long x;
        try {
            SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
            Date d = sdf.parse(currentdate);

            Timestamp appointTime=Timestamp.valueOf(new SimpleDateFormat("yyyy-MM-dd hh:mm:ss").format(d));
            SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd hh:mm:ss");
            Date date = df.parse(String.valueOf(appointTime));
            long s=date.getTime();
            String unixDate=String.valueOf(s).substring(0, 10);
            x=Long.parseLong(unixDate);
            return x;
        } catch (ParseException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
            return 0;
        }
    }

    public static String covertLontToDateString(long date){
        String dateString=new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(new Date(date * 1000));
        return dateString;
    }

    public static String covertTimestampToDateString(Timestamp timestamp,String format){
        String tsStr = "";
        DateFormat sdf = new SimpleDateFormat(format);
        try {
            //方法一
            tsStr = sdf.format(timestamp);
            return tsStr;

        } catch (Exception e) {
            e.printStackTrace();
            return null;
        }


    }

    public static Timestamp DatetoTimestamp(Date date) {
        DateFormat format = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        String datestr;
        datestr = format.format(date);
        return Timestamp.valueOf(datestr);
    }


    public static int getAgeByTimestampBirthDay(Timestamp birthday){
        //SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");

        Date	birthDay=new Date(birthday.getTime());


        Calendar cal = Calendar.getInstance();

        if (cal.before(birthDay)) {
            return -1;
        }
        int yearNow = cal.get(Calendar.YEAR);
        int monthNow = cal.get(Calendar.MONTH);
        int dayOfMonthNow = cal.get(Calendar.DAY_OF_MONTH);
        cal.setTime(birthDay);
        int yearBirth = cal.get(Calendar.YEAR);
        int monthBirth = cal.get(Calendar.MONTH);
        int dayOfMonthBirth = cal.get(Calendar.DAY_OF_MONTH);

        int age = yearNow - yearBirth;

        if (monthNow <= monthBirth) {
            if (monthNow == monthBirth) {
                if (dayOfMonthNow < dayOfMonthBirth) age--;
            }else{
                age--;
            }
        }
        return age;
    }


    //判断时间是否交叉
    public static Boolean isOverLaps(String beginDate1, String endDate1, String beginDate2, String endDate2){
        try{
            SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
            Date date1b = sdf.parse(beginDate1);
            Date date1e = sdf.parse(endDate1);
            Date date2b = sdf.parse(beginDate2);
            Date date2e = sdf.parse(endDate2);

            if(date2b.compareTo(date1e)*date2e.compareTo(date1b)>0) return false;
            else{//判断是否是时间交接点:08:00-12:00 12:00-15:00
                if(date2b.equals(date1e) || date2e.equals(date1b)){
                    return false;
                }else return true;
            }
        }catch(Exception e){
            e.printStackTrace();
            return false;
        }
    }


    public static long getBetweenDayByTimestam(Timestamp start,Timestamp end){


        int days = (int) ((end.getTime() - start.getTime()) / (1000*3600*24));
        return days;
    }

    public static String gbjlFormatForExcel(String gbjl){
        String result="";
        result=gbjl.replace("（", "\n"+"                    (");
        //result=result.replace("(",  "\n"+"                    (");

        return result;
    }


    /**
     * 得到当前日期
     * @return
     */
    public static String getCurrentDate() {
        Calendar c = Calendar.getInstance();
        Date date = c.getTime();
        SimpleDateFormat simple = new SimpleDateFormat("yyyy-MM-dd");
        return simple.format(date);
    }

    public static String filterQymcSpase(String qymc){
        String result=qymc.trim();
        result=result.replace(" ","");
        Pattern p = Pattern.compile("\\s*|\t|\r|\n");
        Matcher m = p.matcher(result);
        result = m.replaceAll("");
        result=result.replace("\u00A0", "");
        return result;



    }

    public static Date getTodayStartTime() {
        Calendar todayStart = Calendar.getInstance();
        todayStart.set(Calendar.HOUR_OF_DAY, 0);
        todayStart.set(Calendar.MINUTE, 0);
        todayStart.set(Calendar.SECOND, 0);
        todayStart.set(Calendar.MILLISECOND, 0);
        return todayStart.getTime();
    }

    //获取23点
    public static Date getTodayEndTime() {
        Calendar todayEnd = Calendar.getInstance();
        todayEnd.set(Calendar.HOUR_OF_DAY, 23);
        todayEnd.set(Calendar.MINUTE, 59);
        todayEnd.set(Calendar.SECOND, 59);
        todayEnd.set(Calendar.MILLISECOND, 999);
        return todayEnd.getTime();
    }


    public static Timestamp covertDateStrToTimeStamp(String datastr,String format){

        Date csrqdate= Tools.convertToDate(datastr,format);

        return new Timestamp(csrqdate.getTime()+6*1000*10);
    }

    public static Timestamp covertDateStrToTimeStamp(String datastr){
        return Tools.covertDateStrToTimeStamp(datastr,"yyyy-MM-dd");

    }


    public static  int getAgeByDate(Date csny){
        Date	birthDay=csny;


        Calendar cal = Calendar.getInstance();

        if (cal.before(birthDay)) {
            return -1;
        }
        int yearNow = cal.get(Calendar.YEAR);
        int monthNow = cal.get(Calendar.MONTH);
        int dayOfMonthNow = cal.get(Calendar.DAY_OF_MONTH);
        cal.setTime(birthDay);
        int yearBirth = cal.get(Calendar.YEAR);
        int monthBirth = cal.get(Calendar.MONTH);
        int dayOfMonthBirth = cal.get(Calendar.DAY_OF_MONTH);

        int age = yearNow - yearBirth;

        if (monthNow <= monthBirth) {
            if (monthNow == monthBirth) {
                if (dayOfMonthNow < dayOfMonthBirth) age--;
            }else{
                age--;
            }
        }
        return age;
    }



    public static byte[] scale(byte[] fileData, int width, int height) {
        ByteArrayInputStream in = new ByteArrayInputStream(fileData);
        try {
            BufferedImage img = ImageIO.read(in);
            if(height == 0) {
                height = (width * img.getHeight())/ img.getWidth();
            }
            if(width == 0) {
                width = (height * img.getWidth())/ img.getHeight();
            }
            Image scaledImage = img.getScaledInstance(width, height, Image.SCALE_SMOOTH);
            BufferedImage imageBuff = new BufferedImage(width, height, BufferedImage.TYPE_INT_RGB);
            imageBuff.getGraphics().drawImage(scaledImage, 0, 0, new Color(0,0,0), null);

            ByteArrayOutputStream buffer = new ByteArrayOutputStream();

            ImageIO.write(imageBuff, "jpg", buffer);

            return buffer.toByteArray();
        } catch (IOException e) {
            e.printStackTrace();
            return null;
        }
    }

    public static Long getPreMonth(String startDate) throws Exception{
        SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd");
        Calendar c = Calendar.getInstance();
        Date date = format.parse(startDate);
        c.setTime(date);
        c.add(Calendar.MONTH, -1);
        return c.getTime().getTime();
    }






}
